package com.dylan.channel.v6.channel;

import com.dylan.channel.v6.EventLoop;
import com.dylan.channel.v6.future.ChannelPromise;

public abstract class AbstractChannel implements Channel {
    private volatile EventLoop eventLoop;

    private final Channel parent;

    private final Channel.Unsafe unsafe;

    protected AbstractChannel(Channel parent) {
        this.parent = parent;
        this.unsafe = this.newUnsafe();
    }
    public Channel.Unsafe unsafe() {
        return this.unsafe;
    }

    @Override
    public EventLoop eventLoop() {
        EventLoop eventLoop = this.eventLoop;
        if (eventLoop == null) {
            throw new IllegalStateException("channel not registered to an event loop");
        }
        return eventLoop;
    }
    /***
     * @Author dylan
     * @Description: 抽象安全操作类
     * @Create: 2024/9/3 13:57
     */
    protected abstract class AbstractUnsafe implements Unsafe {
        @Override
        public void register(EventLoop eventLoop, final ChannelPromise promise) {
            AbstractChannel.this.eventLoop = eventLoop;
            if (eventLoop.inEventLoop(Thread.currentThread())) {
                this.register0(promise);
            } else {
                eventLoop.execute(new Runnable() {
                    @Override
                    public void run() {
                        AbstractUnsafe.this.register0(promise);
                    }
                });
            }
        }

        protected void register0(final ChannelPromise promise) {
            //开始进行注册
            AbstractChannel.this.doRegister();

            //将Promise的结果设置成SUCCESS
            promise.setSuccess(null);
        }
    }
    protected abstract AbstractUnsafe newUnsafe();

    protected abstract void doRegister();
}
